<template>
  <el-container class="advance-query-form advance-box" style="position: relative;">
    <el-aside width="300px">
      <el-card class="base-card" shadow="never">
        <div slot="header" class="base-card-header">
          <span style="color: #333333; font-weight: bold" class="header-title">字典名称</span>
          <div class="base-card-operation">
            <el-button
              class="advance-icon-btn"
              @click="refreshDictNameDropdownList"
              style="width: 40px; height: 32px; padding: 0"
            >
              <img src="@/assets/img/refresh2.png" alt="" style="vertical-align: middle" />
            </el-button>
            <el-button
              class="advance-icon-btn"
              :size="defaultFormItemSize"
              style="width: 40px; height: 32px; padding: 0"
              @click="onAddDictClick()"
            >
              <img src="@/assets/img/add.png" alt="" style="vertical-align: middle" />
            </el-button>
          </div>
        </div>
        <el-scrollbar :style="{height: (getMainContextHeight - 130) + 'px'}" class="custom-scroll">
          <el-tree
            ref="dictId"
            :props="{label: 'name'}"
            :data="listPmDict.dictNameWidget.dropdownList"
            node-key="id"
            current-node-key="id"
            :highlight-current="true"
            :default-expand-all="true"
            @node-click="onDictNameValueChange"
          >
            <div class="module-node-item" slot-scope="{ data }">
              <el-row type="flex" justify="space-between" align="middle" style="margin-right: 9px">
                <span>{{ data.name }}</span>
                <div class="module-node-menu">
                  <el-button
                    type="text"
                    :size="defaultFormItemSize"
                    icon="el-icon-edit-outline"
                    @click.stop="onEditDictClick(data)"
                  />
                  <el-button
                    type="text"
                    :size="defaultFormItemSize"
                    icon="el-icon-delete"
                    @click.stop="onDeleteDictClick(data)"
                  />
                </div>
              </el-row>
            </div>
          </el-tree>
        </el-scrollbar>
      </el-card>
    </el-aside>
    <el-main class="page-box" style="padding-left: 15px; display: flex">
      <table-box
        ref="pmDictType"
        class="page-table"
        :data="listPmDict.pmDictTypeWidget.dataList"
        :size="defaultFormItemSize"
        :row-config="{isCurrent: false, isHover: true}"
        :seq-config="{startIndex: ((listPmDict.pmDictTypeWidget.currentPage - 1) * listPmDict.pmDictTypeWidget.pageSize)}"
        :sort-config="{remote: true}"
        :hasExtend="true"
        :tree-config="{ rowField: 'dataId', parentField: 'parentId' }"
        @sort-change="listPmDict.pmDictTypeWidget.onSortChange"
        @refresh="listPmDict.pmDictTypeWidget.refreshTable()"
        @change="onPmDictTypeSelectionChange"
      >
        <el-button
          slot="operator"
          type="primary"
          :size="defaultFormItemSize"
          :disabled="!checkPermCodeExist('listPmDict:listPmDict:addDictData')"
          @click="onAddDictDataClick()"
        >
          新建
        </el-button>
        <el-button
          slot="operator"
          type="primary"
          :size="defaultFormItemSize"
          :disabled="listPmDict.pmDictTypeBatchSelectRows.length <= 0 || !checkPermCodeExist('listPmDict:listPmDict:batchDelete')"
          @click="onBatchDeleteClick()"
        >
          批量删除
        </el-button>
        <vxe-column fixed="left" type="checkbox" :width="40" />
        <vxe-column title="序号" fixed="left" type="seq" :index="listPmDict.pmDictTypeWidget.getTableIndex" :width="80" tree-node />
        <vxe-column title="字典值" field="dictValue" />
        <vxe-column title="字典标签" field="dictLabel" />
        <vxe-column title="字典排序" field="dictSort" sortable />
        <vxe-column title="操作" fixed="right">
          <template slot-scope="scope">
            <el-button
              type="text"
              :size="defaultFormItemSize"
              @click.stop="onEditDictDataClick(scope.row)"
              :disabled="!checkPermCodeExist('listPmDict:listPmDict:editDictData')"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              :size="defaultFormItemSize"
              @click.stop="onDeleteDictDataClick(scope.row)"
              :disabled="!checkPermCodeExist('listPmDict:listPmDict:deleteDictData')"
            >
              删除
            </el-button>
          </template>
        </vxe-column>
        <template slot="empty">
          <div class="table-empty unified-font">
            <img src="@/assets/img/empty.png">
            <span>暂无数据</span>
          </div>
        </template>
      </table-box>
      <label v-if="subPage" class="page-close-box" @click="onCancel(true)">
        <img src="@/assets/img/back2.png" alt="">
      </label>
    </el-main>
  </el-container>
</template>

<script>
import { mapGetters } from 'vuex';
import rules from '@/utils/validate';
import { stringCase, treeDataTranslate, findItemFromList, findTreeNodePath, findTreeNode } from '@/utils';
import { uploadMixin, statsDateRangeMixin, cachePageMixin } from '@/core/mixins';
import { DropdownWidget, TableWidget, UploadWidget, ChartWidget } from '@/utils/widget.js';
import FormEditPmDictType from '@/views/PmDictMng/formEditPmDictType.vue';
import FormEditPmDictData from '@/views/PmDictMng/formEditPmDictData.vue';
import { PmDictDataController, PmDictTypeController, DictionaryController } from '@/api';

export default {
  name: 'listPmDict',
  props: {
    subPage: {
      type: [Number, String, Boolean],
      default: 0
    }
  },
  mixins: [uploadMixin, statsDateRangeMixin, cachePageMixin],
  data () {
    return {
      formData: {
        PmDictType: {
          // 主键ID
          dictId: undefined,
          // 字典名称
          dictName: undefined,
          // 字典分类(L-列表字典,T-树形字典)
          dictCategory: undefined,
          // 备注
          remark: undefined,
          isDatasourceInit: false
        }
      },
      formFilter: {
        dictId: undefined,
      },
      formFilterCopy: {
        dictId: undefined,
      },
      listPmDict: {
        // 字典数据数据源批量删除或者批量更新选中数据
        pmDictTypeBatchSelectRows: [],
        // 字典数据数据源组件
        pmDictTypeWidget: new TableWidget(this.loadPmDictTypeWidgetData, this.loadPmDictTypeVerify, false, false, 'dictSort', true),
        // 字典名称组件
        dictNameWidget: new DropdownWidget(this.loadDictNameDropdownList, true, 'id', 'parentId'),
        isInit: false
      },
    }
  },
  methods: {
    onCancel (isSuccess) {
      this.removeCachePage(this.$options.name);
      this.refreshParentCachedPage = isSuccess;
      this.$router.go(-1);
    },
    refreshDictNameDropdownList() {
      this.listPmDict.dictNameWidget.reloadDropdownData().then(dataList => {
        if (
          !Array.isArray(dataList) ||
          dataList.find(item => item.id === this.formFilter.dictId) == null
        ) {
          this.formFilter.dictId = undefined;
          this.formFilterCopy.dictId = undefined;
        }
        this.$refs.dictId.setCurrentKey(this.formFilter.dictId);
      });
    },
    onAddDictClick() {
      this.$dialog
        .show(
          '新建',
          FormEditPmDictType,
          { area: '600px' },
          {}
        )
        .then(res => {
          this.refreshDictNameDropdownList();
        })
        .catch(() => {
          console.log('cancel');
        });
    },
    onEditDictClick(data) {
      let params = {
        dictId: data.id
      };
      this.$dialog
        .show(
          '编辑',
          FormEditPmDictType,
          { area: '900px' },
          params
        )
        .then(res => {
          this.refreshDictNameDropdownList();
        })
        .catch(() => {
          console.log('cancel');
        });
    },
    onDeleteDictClick(data) {
      let params = {
        dictId: data.id
      };
      this.$confirm('是否删除选中的数据?')
        .then(() => {
          return PmDictTypeController.delete(this, params);
        })
        .then(() => {
          this.$message.success('删除成功');
          this.refreshDictNameDropdownList();
        })
        .catch(() => {
          console.log('cancel');
        });
    },
    /**
     * 字典数据数据源数据获取函数，返回Promise
     */
    loadPmDictTypeWidgetData (params) {
      if (!this.formFilter.dictId) {
        return new Promise((resolve, reject) => {
          resolve({
            dataList: [],
            totalCount: 0
          })
        });
      }

      if (params == null) params = {};
      params = {
        ...params,
        pmDictDataDtoFilter: {
          dictId: this.formFilter.dictId
        }
      };
      return new Promise((resolve, reject) => {
        PmDictDataController.list(this, params).then(res => {
          // 列表数据转换成树形数据
          res.data.dataList = treeDataTranslate(
            res.data.dataList,
            'dataId',
            'parentId'
          );
          resolve({
            dataList: res.data.dataList,
            totalCount: res.data.totalCount
          });
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 字典数据数据源数据获取检测函数，返回true正常获取数据，返回false停止获取数据
     */
    loadPmDictTypeVerify() {
      this.formFilterCopy.dictId = this.formFilter.dictId;
      return true;
    },
    /**
     * 字典数据数据源表格批量操作
     */
    onPmDictTypeSelectionChange (values) {
      this.listPmDict.pmDictTypeBatchSelectRows = values || [];
    },
    /**
     * 新建
     */
    onAddDictDataClick(row) {
      let params = {
        dictId: this.formFilter.dictId,
      };

      if (!this.formFilter.dictId) {
        this.$message.error('请选择字典');
        return;
      }

      this.$dialog
        .show('新建', FormEditPmDictData, { area: '900px' }, { ...params, subPage: true })
        .then(res => {
          this.listPmDict.pmDictTypeWidget.refreshTable();
        })
        .catch(e => {});
    },
    /**
     * 批量删除
     */
    onBatchDeleteClick(row) {
      let params = {
      };

      this.$confirm('是否删除选中数据？').then(res => {
        params.dataIdList = this.listPmDict.pmDictTypeBatchSelectRows.map(item => item.dataId);
        PmDictDataController.deleteBatch(this, params).then(res => {
          this.$message.success('删除成功');
          this.listPmDict.pmDictTypeBatchSelectRows = [];
          this.listPmDict.pmDictTypeWidget.refreshTable(true, 1);
        }).catch(e => {});
      }).catch(e => {});
    },
    /**
     * 编辑
     */
    onEditDictDataClick(row) {
      let params = {
        dataId: row.dataId
      };

      this.$dialog
        .show('编辑', FormEditPmDictData, { area: '900px' }, { ...params, subPage: true })
        .then(res => {
          this.listPmDict.pmDictTypeWidget.refreshTable();
        })
        .catch(e => {});
    },
    /**
     * 删除
     */
    onDeleteDictDataClick(row) {
      let params = {
        dataId: row.dataId
      };

      this.$confirm('是否删除当前数据').then(res => {
        PmDictDataController.delete(this, params).then(res => {
          this.$message.success('删除成功');
          this.listPmDict.pmDictTypeWidget.refreshTable(false, 1);
        }).catch(e => {});
      }).catch(e => {});
    },
    /**
     * 字典名称下拉数据获取函数
     */
    loadDictNameDropdownList() {
      return new Promise((resolve, reject) => {
        const params = {
        };
        DictionaryController.dictPmDict(this, params).then(res => {
          resolve(res.getList());
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 字典名称选中值改变
     */
    onDictNameValueChange(value) {
      if (value.id !== this.formFilter.dictId) {
        this.formFilter.dictId = value.id;
      } else {
        this.formFilter.dictId = undefined;
        this.$nextTick(() => {
          this.$refs.dictId.setCurrentKey(null);
        });
      }
      this.refreshListPmDict(true);
    },
    refreshListPmDict(reloadData = false) {
      this.listPmDict.pmDictTypeWidget.refreshTable(reloadData, reloadData ? 1 : undefined);
    },
    /**
     * 重置过滤值
     */
    resetListPmDict() {
      this.formFilter.dictId = undefined;
      this.formFilterCopy.dictId = undefined;
      this.refreshListPmDict();
    },
    /**
     * 重置所有过滤值
     */
    resetFilter () {
      this.resetListPmDict();
    },
    onResume () {
      this.refreshListPmDict();
    },
    formInit() {
      this.listPmDict.dictNameWidget.onVisibleChange(true).catch(e => {});
      this.refreshListPmDict();
    }
  },
  mounted () {
    // 初始化页面数据
    this.formInit();
  },
  computed: {
    ...mapGetters(['getMainContextHeight'])
  }
}
</script>

<style scoped>
::v-deep .el-tree-node__content {
  height: 35px;
}
.module-node-item {
  width: 100%;
  height: 35px;
  line-height: 35px;
}
</style>
